package org.zhuxian.cn.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zhuxian.cn.entity.Cultivation;
import org.zhuxian.cn.mapper.CultivationMapper;
import org.zhuxian.cn.service.CultivationService;
import org.zhuxian.cn.utils.RedisUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class CultivationServiceImpl implements CultivationService {
    @Autowired
    private CultivationMapper cultivationMapper;

    @Autowired
    private RedisUtils redisUtils;

    private static String CULTIVATION_KEY = "clutivation:all";

    @Override
    public void addCultivation(Cultivation cultivation) {
        cultivationMapper.insert(cultivation);
    }

    @Override
    public void updateCultivation(Cultivation cultivation) {
        cultivationMapper.updateById(cultivation);
    }

    @Override
    public void deleteCultivation(Cultivation cultivation) {
        cultivationMapper.deleteById(cultivation.getId());
    }

    @Override
    public List<Cultivation> getAllCultivation() {
        List<Cultivation> cultivations = redisUtils.get(CULTIVATION_KEY, List.class);
        if (cultivations == null || cultivations.isEmpty()) {
            cultivations = cultivationMapper.selectList(null);
            redisUtils.setEx(CULTIVATION_KEY, cultivations, 3, TimeUnit.MINUTES);
        }
        return cultivations;
    }
}
